package com.cman777.springc.web.util;

import com.cman777.springc.common.bean.response.JsonResult;
import com.cman777.springc.common.helper.JsonHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

public abstract class ServletResponseUtil
{
    private static final Logger log;
    public static final String DEFAULT_CONTENT_TYPE = "text/html;charset=UTF-8";
    
    public static void write(final ServletResponse servletResponse, final JsonResult jsonResult) {
        final String text = JsonHelper.toJsonStringQuietly((Object)jsonResult);
        write(servletResponse, text);
    }
    
    public static void write(final ServletResponse servletResponse, final String text) {
        final String[] texts = { "" };
        Optional.ofNullable(text).ifPresent(value0 -> texts[0] = value0);
        servletResponse.setContentLength(texts[0].getBytes().length);
        servletResponse.setContentType("text/html;charset=UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        try {
            final PrintWriter printWriter = servletResponse.getWriter();
            printWriter.write(texts[0]);
            printWriter.flush();
            printWriter.close();
        }
        catch (IOException e) {
            ServletResponseUtil.log.error("ServletResponse获取writer失败:{}", (Throwable)e);
        }
    }
    
    static {
        log = LogManager.getLogger((Class)ServletResponseUtil.class);
    }
}
